package com.xh.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;

/**
 * description: ChatHandler <br>
 * date: 2021/11/14 1:31 <br>
 * author: xiehui <br>
 * version: 1.0 <br>
 */

public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    // 用于记录和管理所有客户端的channel
    private ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        String text = msg.text();
        System.out.println("接收到的数据是："+text);

        // 将数据刷新到客户端
        clients.writeAndFlush( new TextWebSocketFrame("[服务器在：]"+ LocalDateTime.now()+",接收到的消息是："+text) );
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        clients.add(ctx.channel());
        System.out.println("助手类添加...");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        //clients.remove(ctx.channel());
        System.out.println("客户端断开，channel对应的长id为："+ctx.channel().id().asLongText());
        System.out.println("客户端断开，channel对应的短id为："+ctx.channel().id().asShortText());
    }
}
